<style scoped lang="scss">
    #container {
        border: 1px solid #ddd;
    }

    .dnd-wrap {
        border: 1px solid #ddd;
        min-width: 120px;
        boredr-right: none;

        .node-box {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 50px;
            border: 1px solid #ddd;
            cursor: move;
            width: 100%;

            .title {
                font-size: 12px;
            }
        }


    }

    #leftMenu {
        position: absolute;

        ul {
            list-style: none;
            border: 1px solid #ddd;
            margin-left: 0px;
            padding-left: 0px;;

            li {
                width: 120px;;
                line-height: 30px;
                cursor: pointer;
                padding-left: 5px;
                background: #fff;

                &:hover {
                    background: #ddd;
                }
            }
        }

    }
</style>
<template>
    <div style="display:flex;">
    代码生产器

    </div>
</template>
<script>
  import { copyToClipboard } from '@/utils/cutparse.js';
  import { alertSuccess, safeParseJson, alertFail } from '@base/utils';
  import MyDialogPlus from '@codegenarate/mydialogplus';




  export default {
    data() {
      return {
        graph: null,
        dnd: null,
        currentItem: undefined,
        rumtimeNodesData: [],
      };
    },
    components: {},
    mounted() {

    },

    methods: {
      /**
       * @params .options .pipNo
       * @params .options .bpmId
       * @desc
       * @return
       */
      async initByDialog(options) {
        var self = this;
        this.pipNo = options.pipNo;
        this.bpmId = options.bpmId;

        if (!this.pipNo || !this.bpmId) {
          alertFail('没有   pipNo   bpmId');
          return { success: false };
        }

        var { graph } = init('container', {});
        this.graph = graph;

        var result = (await this.getJsonbybnpmId(this.bpmId));
        var json = result && result.data;
        //默认 填充一些默认的width height
        var nodes = json && json.nodes || [];
        for (let i = 0; i < nodes.length; i++) {
          var nodeName = nodes[i].nodeName;
          nodes[i].id = `${nodes[i].id || 0}`;
          nodes[i].data = deepClone(nodes[i]);

          if (nodeName == '开始') {
            nodes[i].shape = 'start-event';
            nodes[i].label = nodeName;
            nodes[i].width = 50;
            nodes[i].height = 50;

          } else if (nodeName == '结束') {
            nodes[i].shape = 'end-event';
            nodes[i].label = nodeName;
            nodes[i].width = 50;
            nodes[i].height = 50;
          } else {
            nodes[i].shape = 'activity';
            nodes[i].label = nodeName;
            nodes[i].width = 100;
            nodes[i].height = 50;
          }


        }

        var edges1 = json && json.mesBpmLines || [];
        var newEdages = [];
        for (let i = 0; i < edges1.length; i++) {
          var exitSourceNode = findOne(nodes, item => item.id == edges1[i].sourceNodeId);
          var exitTargetNode = findOne(nodes, item => item.id == edges1[i].targetNodeId);
          if (!(exitSourceNode && exitTargetNode)) {
            continue;
          }
          newEdages.push({
            shape: 'bpmn-edge',
            data: edges1[i],
            id: edges1[i].id,
            source: {
              cell: `${edges1[i].sourceNodeId}`,
              port: 'port3',
            },
            target: {
              cell: `${edges1[i].targetNodeId}`,
              connectionPoint: 'boundary', // 没有参数时可以简化写法
            },
          });
        }


        var temjson = {
          nodes: json.nodes,
          edges: newEdages,
        };
        var layout = new DagreLayout({
          type: 'dagre',
          rankdir: 'T', // 可选，默认为图的中心
        });
        console.log('temjson', JSON.stringify(temjson));
        const newmodel = layout.layout(temjson);
        //debugger
        this.graph.fromJSON(newmodel);


        //控制 line 有表达式的特色标记
        this.setConditionLineRect(newEdages);

        //获取流程图的rumtimenode
        this.rumtimeNodesData = await this.getRumTimeNodes();
        //加入 state  节点绘制 color
        this.fillColorByStateForNode(this.rumtimeNodesData);

      },
      //控制 line 有表达式的特色标记
      setConditionLineRect(lines) {
        for (let i = 0; i < lines.length; i++) {
          var cell = this.graph.getCellById(lines[i].id);
          if (lines[i] && lines[i].data && lines[i].data.exitCondition /*有表达式*/) {
            cell.setAttrByPath('signRect/opacity', 1);
          }
        }
      },
      getNodeName(oneData) {
        if (oneData.nodeName == '开始' || oneData.nodeName == '结束') {
          return `${oneData.nodeName}`;
        }
        return `${oneData.nodeName}/${oneData.currentUserName}`;
      },

      fillColorByStateForNode(rumtimeNodesData = []) {
        for (let i = 0; i < rumtimeNodesData.length; i++) {
          var oneData = rumtimeNodesData[i];
          if (oneData.id) {
            console.log('oneData.id ', oneData.nodeName, oneData.nodeId);
            var cellnode = this.graph.getCellById(`${oneData.nodeId}`);
            if (cellnode) {
              if (cellnode && oneData && oneData.state == 15) {
                cellnode.setAttrByPath('body/fill', '#ddd');
                cellnode.setAttrByPath('body/stroke', '#ddd');
                cellnode.setAttrByPath('label/text', this.getNodeName(oneData));
              } else if (cellnode && oneData && oneData.state == 10) {
                cellnode.setAttrByPath('body/fill', '#eff4ff');
                cellnode.setAttrByPath('label/text',this.getNodeName(oneData));
              } else if (cellnode && oneData && oneData.state == 15) {
                cellnode.setAttrByPath('body/fill', '#eff4ff');
                cellnode.setAttrByPath('label/text',this.getNodeName(oneData));
              }
            }
          }

        }
      },

      async getRumTimeNodes() {
        var result = await plmProductDevelopmentPipelineApi.getList({
          pipNo: this.pipNo,
          pageNum: 1,
          pageSize: 999,
        });
        return result && result.data || [];
      },

      async getJsonbybnpmId(id) {
        if (!id) return undefined;
        var json = await bpnmApi.getJsonbyBnpmId({ bpmId: id });
        return json;
      },

      async startDrag(e) {
        let data = undefined;
        var node = undefined;
        var type = e.currentTarget.dataset.type;
        //var id = createUuid();
        if (type === 'activity') {
          node = this.graph.createNode({
            shape: type,
          });
        } else if (type === 'start-event') {
          node = this.graph.createNode({
            shape: type,
            attrs: {
              label: {
                text: '开始',
              },
            },
          });
        } else if (type === 'end-event') {
          node = this.graph.createNode({
            shape: type,
            attrs: {
              label: {
                text: '结束',
              },
            },
          });
        } else if (type === 'gateway') {
          node = this.graph.createNode({
            shape: type,
          });
        }

        console.log('node', node, e);
        this.dnd.start(node, e);
      },
      removeNode() {
        var nodeId = sessionStorage.getItem('contextmenu_current_node_id');
        var cell = this.graph.getCellById(nodeId);
        if (cell && cell.id) {
          this.graph.removeNode(cell.id);
          document.documentElement.querySelector('#leftMenu').style.display = 'none';

          //axois  删除节点
          if (cell.shape == 'activity' ||
            cell.shape == 'end-event' ||
            cell.shape == 'start-event') {
            axios.get('/api1/mesBpmPipeline/deleteNodeById?id=' + cell.id);
          } else if (cell.shape == 'bpmn-edge') {
            axios.get('/api1/mesBpmPipeline/deleteEdageById?id=' + cell.id);
          }

        }
      },
      async triggerEdit() {
        var nodeId = sessionStorage.getItem('contextmenu_current_node_id');
        if (nodeId) {
          var cellItem = this.graph.getCellById(nodeId);
          var result = await MyDialogPlus({
            title: '导入json',
            components: {
              modify: () => import('@/dialog/importin.vue'),
            },
          });
        }

      },
      /**
       * @description: 暂时缓存
       * @params
       * @return
       */
      triggerSave() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('json', json);
        copyToClipboard(JSON.stringify(json));
        alertSuccess('已复制到粘贴板上');
        sessionStorage.setItem('save_json_graph', JSON.stringify(json));
      },
      /**
       * @description:
       * @params
       * @return
       */
      async triggerSavetoback() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('json', json);
        copyToClipboard(JSON.stringify(json));
        //alertSuccess('已复制到粘贴板上');
        sessionStorage.setItem('save_json_graph', JSON.stringify(json));


        var nodes = [];
        var mesBpmLines = [];
        for (let i = 0; i < json.cells.length; i++) {
          var cell = json.cells[i];
          if (cell.shape === 'activity') {
            cell.thirdPartId = cell.id;
            nodes.push(cell.data);
          } else if (cell.shape === 'end-event') {
            cell.thirdPartId = cell.id;
            nodes.push(cell.data);
          } else if (cell.shape === 'start-event') {
            cell.thirdPartId = cell.id;
            nodes.push(cell.data);
          } else if (cell.shape === 'bpmn-edge') {

            var sourceNode = this.graph.getCellById(cell.source.cell);
            var targetNode = this.graph.getCellById(cell.target.cell);
            mesBpmLines.push({
              sourceNodeId: sourceNode && sourceNode.data && sourceNode.data.id,
              targetNodeId: targetNode && targetNode.data && targetNode.data.id,
            });
          }
        }
        const result = await axios.post('/api1/mesBpmPipeline/saveComprehensive', {
          bpmId: 2,
          nodes,
          mesBpmLines,
        });
        if (result && result.success) {
          alertSuccess('保存成功');
        }
      },


      /**
       * @description:  加载数据
       * @params
       * @return
       */
      async triggerRemote() {
        const resultEntity = await axios.post('/api1/mesBpmPipeline/listComprehensive', {
          bpmId: 2,
        }).then(res => res.data);

        var data = resultEntity.data;
        var nodes = data.nodes || [];
        var edges = data.mesBpmLines || [];

        var newNodes = [];
        var newEdages = [];


        for (let i = 0; i < nodes.length; i++) {
          var one = nodes[i];
          var oneNode = undefined;
          if (one.nodeName == '开始') {
            oneNode = ({
              shape: 'start-event',
              id: `${one.id}`,
              data: one,
              width: 50,
              height: 50,
              attrs: {
                width: 50,
                height: 50,
                label: { text: one.nodeName },
              },
            });
          } else if (one.nodeName == '结束') {
            oneNode = ({
              shape: 'end-event',
              id: `${one.id}`,
              data: one,
              width: 50,
              height: 50,
              attrs: {
                width: 50,
                height: 50,
                label: { text: one.nodeName },
              },
            });
          } else {
            oneNode = ({
              shape: 'activity',
              id: `${one.id}`,
              data: one,
              width: 100,
              height: 50,
              label: `${one.id}--${one.nodeName}`,
              attrs: {
                width: 100,
                height: 50,
              },
            });
          }

          newNodes.push(oneNode);

        }


        /*================  开始 画线 */
        for (let i = 0; i < edges.length; i++) {
          var edge = edges[i];
          newEdages.push({
            id: edge.id,
            shape: 'bpmn-edge',
            //label: '我是表达式',
            source: {
              cell: `${edge.sourceNodeId}`,
              port: 'port3',
            },
            target: {
              cell: `${edge.targetNodeId}`,
              connectionPoint: 'boundary', // 没有参数时可以简化写法
            },
          });
        }


        const model = { nodes: newNodes, edges: newEdages };


        var layout = new DagreLayout({
          type: 'dagre',
          rankdir: 'T', // 可选，默认为图的中心
        });
        const newmodel = layout.layout(model);
        this.graph.fromJSON(newmodel);
      },

      triggerJSON() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('json', json);
        copyToClipboard(JSON.stringify(json));
        alertSuccess('已复制到粘贴板上');
      },
      async triggerImportJson() {

        var result = await MyDialogPlus({
          title: '导入json',
          components: {
            modify: () => import('@/dialog/importin.vue'),
          },

        });
        if ((result && result.success)) {
          var json = JSON.parse(result.data);
          this.graph.fromJSON(json);
          alertSuccess('导入成功');

        }

      },

    },
  };
</script>
